{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0a9d6ab2",
   "metadata": {},
   "source": [
    "# Conversion of the dataset to fit the nnUNet"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c3543035-4547-45f1-aaa6-c8491e44f87f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import shutil\n",
    "import os\n",
    "import SimpleITK as sitk\n",
    "import numpy as np\n",
    "\n",
    "def copy_BraTS_segmentation_and_convert_labels_to_nnUNet_2024(in_file: str, out_file: str) -> None:\n",
    "    # use this for segmentation only!!!\n",
    "    # nnUNet wants the labels to be continuous. BraTS is 0, 1, 2, 3, 4 -> we make that into 0, 1, 2, 3, 4\n",
    "    img = sitk.ReadImage(in_file)\n",
    "    img_npy = sitk.GetArrayFromImage(img)\n",
    "\n",
    "    uniques = np.unique(img_npy)\n",
    "    #for u in uniques:\n",
    "        #if u not in [0, 1, 2, 4]:\n",
    "         #   raise RuntimeError('unexpected label')\n",
    "\n",
    "    seg_new = np.zeros_like(img_npy)\n",
    "    seg_new[img_npy == 3] = 3\n",
    "    seg_new[img_npy == 2] = 1\n",
    "    seg_new[img_npy == 1] = 2\n",
    "    seg_new[img_npy == 4] = 4\n",
    "    seg_new[img_npy < 0] = 0\n",
    "    seg_new[img_npy > 5] = 0\n",
    "    img_corr = sitk.GetImageFromArray(seg_new)\n",
    "    img_corr.CopyInformation(img)\n",
    "    sitk.WriteImage(img_corr, out_file)\n",
    "\n",
    "def copy_BraTS_segmentation_and_convert_labels_to_nnUNet_2023(in_file: str, out_file: str) -> None:\n",
    "    # use this for segmentation only!!!\n",
    "    # nnUNet wants the labels to be continuous. BraTS is 0, 1, 2, 3 -> we make that into 0, 1, 2, 3\n",
    "    img = sitk.ReadImage(in_file)\n",
    "    img_npy = sitk.GetArrayFromImage(img)\n",
    "\n",
    "    uniques = np.unique(img_npy)\n",
    "    #for u in uniques:\n",
    "        #if u not in [0, 1, 2, 4]:\n",
    "         #   raise RuntimeError('unexpected label')\n",
    "\n",
    "    seg_new = np.zeros_like(img_npy)\n",
    "    seg_new[img_npy == 3] = 3\n",
    "    seg_new[img_npy == 2] = 1\n",
    "    seg_new[img_npy == 1] = 2\n",
    "    seg_new[img_npy < 0] = 0\n",
    "    seg_new[img_npy > 4] = 0\n",
    "    img_corr = sitk.GetImageFromArray(seg_new)\n",
    "    img_corr.CopyInformation(img)\n",
    "    sitk.WriteImage(img_corr, out_file)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4a4bdd32",
   "metadata": {},
   "outputs": [],
   "source": [
    "# https://github.com/MIC-DKFZ/MedNeXt/blob/main/nnunet_mednext/dataset_conversion/utils.py\n",
    "\n",
    "#    Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany\n",
    "#\n",
    "#    Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "#    you may not use this file except in compliance with the License.\n",
    "#    You may obtain a copy of the License at\n",
    "#\n",
    "#        http://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "#    Unless required by applicable law or agreed to in writing, software\n",
    "#    distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "#    See the License for the specific language governing permissions and\n",
    "#    limitations under the License.\n",
    "\n",
    "from typing import Tuple\n",
    "import numpy as np\n",
    "from batchgenerators.utilities.file_and_folder_operations import *\n",
    "\n",
    "def get_identifiers_from_splitted_files(folder: str):\n",
    "    uniques = np.unique([i[:-12] for i in subfiles(folder, suffix='.nii.gz', join=False)])\n",
    "    return uniques\n",
    "\n",
    "def generate_dataset_json(output_file: str, imagesTr_dir: str, imagesTs_dir: str, modalities: Tuple,\n",
    "                          labels: dict, dataset_name: str, sort_keys=True, license: str = \"hands off!\", dataset_description: str = \"\",\n",
    "                          dataset_reference=\"\", dataset_release='0.0'):\n",
    "    \"\"\"\n",
    "    :param output_file: This needs to be the full path to the dataset.json you intend to write, so\n",
    "    output_file='DATASET_PATH/dataset.json' where the folder DATASET_PATH points to is the one with the\n",
    "    imagesTr and labelsTr subfolders\n",
    "    :param imagesTr_dir: path to the imagesTr folder of that dataset\n",
    "    :param imagesTs_dir: path to the imagesTs folder of that dataset. Can be None\n",
    "    :param modalities: tuple of strings with modality names. must be in the same order as the images (first entry\n",
    "    corresponds to _0000.nii.gz, etc). Example: ('T1', 'T2', 'FLAIR').\n",
    "    :param labels: dict with int->str (key->value) mapping the label IDs to label names. Note that 0 is always\n",
    "    supposed to be background! Example: {0: 'background', 1: 'edema', 2: 'enhancing tumor'}\n",
    "    :param dataset_name: The name of the dataset. Can be anything you want\n",
    "    :param sort_keys: In order to sort or not, the keys in dataset.json\n",
    "    :param license:\n",
    "    :param dataset_description:\n",
    "    :param dataset_reference: website of the dataset, if available\n",
    "    :param dataset_release:\n",
    "    :return:\n",
    "    \"\"\"\n",
    "    train_identifiers = get_identifiers_from_splitted_files(imagesTr_dir)\n",
    "\n",
    "    if imagesTs_dir is not None:\n",
    "        test_identifiers = get_identifiers_from_splitted_files(imagesTs_dir)\n",
    "    else:\n",
    "        test_identifiers = []\n",
    "\n",
    "    json_dict = {}\n",
    "    json_dict['name'] = dataset_name\n",
    "    json_dict['description'] = dataset_description\n",
    "    json_dict['tensorImageSize'] = \"4D\"\n",
    "    json_dict['reference'] = dataset_reference\n",
    "    json_dict['licence'] = license\n",
    "    json_dict['release'] = dataset_release\n",
    "    json_dict['modality'] = {str(i): modalities[i] for i in range(len(modalities))}\n",
    "    json_dict['labels'] = {str(i): labels[i] for i in labels.keys()}\n",
    "\n",
    "    json_dict['numTraining'] = len(train_identifiers)\n",
    "    json_dict['numTest'] = len(test_identifiers)\n",
    "    json_dict['training'] = [\n",
    "        {'image': \"./imagesTr/%s.nii.gz\" % i, \"label\": \"./labelsTr/%s.nii.gz\" % i} for i\n",
    "        in\n",
    "        train_identifiers]\n",
    "    json_dict['test'] = [\"./imagesTs/%s.nii.gz\" % i for i in test_identifiers]\n",
    "\n",
    "    if not output_file.endswith(\"dataset.json\"):\n",
    "        print(\"WARNING: output file name is not dataset.json! This may be intentional or not. You decide. \"\n",
    "              \"Proceeding anyways...\")\n",
    "    save_json(json_dict, os.path.join(output_file), sort_keys=sort_keys)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa190f49",
   "metadata": {},
   "source": [
    "## BraTS 2023 Task 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b019ecc7-0e4f-41b9-82f0-8da2fe5f3b54",
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def convert_to_nnUNet_2023_real(source_file, destination_folder):\n",
    "    os.makedirs(os.path.join(destination_folder, \"imagesTr\"), exist_ok=True)\n",
    "    os.makedirs(os.path.join(destination_folder, \"labelsTr\"), exist_ok=True)\n",
    "    for folder in os.listdir(source_file):\n",
    "        t1c_name = f\"{folder}-t1c.nii.gz\"\n",
    "        t1c_path = os.path.join(source_file, folder, t1c_name)\n",
    "        new_t1c_name = f\"{folder}_0000.nii.gz\"\n",
    "        destination_t1c = os.path.join(destination_folder, \"imagesTr\", new_t1c_name)\n",
    "        shutil.copy(t1c_path, destination_t1c)\n",
    "        \n",
    "        t1n_name = f\"{folder}-t1n.nii.gz\"\n",
    "        t1n_path = os.path.join(source_file, folder, t1n_name)\n",
    "        new_t1n_name = f\"{folder}_0001.nii.gz\"\n",
    "        destination_t1n = os.path.join(destination_folder, \"imagesTr\", new_t1n_name)\n",
    "        shutil.copy(t1n_path, destination_t1n)\n",
    "        \n",
    "        t2f_name = f\"{folder}-t2f.nii.gz\"\n",
    "        t2f_path = os.path.join(source_file, folder, t2f_name)\n",
    "        new_t2f_name = f\"{folder}_0002.nii.gz\"\n",
    "        destination_t2f = os.path.join(destination_folder, \"imagesTr\", new_t2f_name)\n",
    "        shutil.copy(t2f_path, destination_t2f)\n",
    "        \n",
    "        t2w_name = f\"{folder}-t2w.nii.gz\"\n",
    "        t2w_path = os.path.join(source_file, folder, t2w_name)\n",
    "        new_t2w_name = f\"{folder}_0003.nii.gz\"\n",
    "        destination_t2w = os.path.join(destination_folder, \"imagesTr\", new_t2w_name)\n",
    "        shutil.copy(t2w_path, destination_t2w)\n",
    "        \n",
    "\n",
    "        seg_name = f\"{folder}-seg.nii.gz\"\n",
    "        seg_path = os.path.join(source_file, folder, seg_name)\n",
    "        new_seg_name = f\"{folder}.nii.gz\"\n",
    "        destination_seg = os.path.join(destination_folder, \"labelsTr\", new_seg_name)\n",
    "        copy_BraTS_segmentation_and_convert_labels_to_nnUNet_2023(in_file=seg_path, out_file=destination_seg)\n",
    "\n",
    "# For real data\n",
    "source_file = '../GliGAN/DataSet/ASNR-MICCAI-BraTS2023-GLI-Challenge-TrainingData'  # Path to the source file\n",
    "destination_folder = './nnUNet_raw/Dataset232_BraTS_2023_rGANs'  # Destination folder path  \n",
    "convert_to_nnUNet_2023_real(source_file, destination_folder)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "67d6a19e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def convert_to_nnUNet_2023_fake(source_file, destination_folder):\n",
    "    os.makedirs(os.path.join(destination_folder, \"imagesTr\"), exist_ok=True)\n",
    "    os.makedirs(os.path.join(destination_folder, \"labelsTr\"), exist_ok=True)\n",
    "    for folder in os.listdir(source_file):\n",
    "        t1c_name = f\"{folder}-scan_t1ce.nii.gz\"\n",
    "        t1c_path = os.path.join(source_file, folder, t1c_name)\n",
    "        new_t1c_name = f\"{folder}_0000.nii.gz\"\n",
    "        destination_t1c = os.path.join(destination_folder, \"imagesTr\", new_t1c_name)\n",
    "        shutil.copy(t1c_path, destination_t1c)\n",
    "        \n",
    "        t1n_name = f\"{folder}-scan_t1.nii.gz\"\n",
    "        t1n_path = os.path.join(source_file, folder, t1n_name)\n",
    "        new_t1n_name = f\"{folder}_0001.nii.gz\"\n",
    "        destination_t1n = os.path.join(destination_folder, \"imagesTr\", new_t1n_name)\n",
    "        shutil.copy(t1n_path, destination_t1n)\n",
    "        \n",
    "        t2f_name = f\"{folder}-scan_flair.nii.gz\"\n",
    "        t2f_path = os.path.join(source_file, folder, t2f_name)\n",
    "        new_t2f_name = f\"{folder}_0002.nii.gz\"\n",
    "        destination_t2f = os.path.join(destination_folder, \"imagesTr\", new_t2f_name)\n",
    "        shutil.copy(t2f_path, destination_t2f)\n",
    "        \n",
    "        t2w_name = f\"{folder}-scan_t2.nii.gz\"\n",
    "        t2w_path = os.path.join(source_file, folder, t2w_name)\n",
    "        new_t2w_name = f\"{folder}_0003.nii.gz\"\n",
    "        destination_t2w = os.path.join(destination_folder, \"imagesTr\", new_t2w_name)\n",
    "        shutil.copy(t2w_path, destination_t2w)\n",
    "        \n",
    "\n",
    "        seg_name = f\"{folder}-seg.nii.gz\"\n",
    "        seg_path = os.path.join(source_file, folder, seg_name)\n",
    "        new_seg_name = f\"{folder}.nii.gz\"\n",
    "        destination_seg = os.path.join(destination_folder, \"labelsTr\", new_seg_name)\n",
    "        copy_BraTS_segmentation_and_convert_labels_to_nnUNet_2023(in_file=seg_path, out_file=destination_seg)\n",
    "\n",
    "# For fake data\n",
    "source_file = '../GliGAN/Checkpoint/brats2023/Synthetic_dataset_random_labels'  # Path to the source file\n",
    "destination_folder = './nnUNet_raw/Dataset232_BraTS_2023_rGANs'  # Destination folder path  \n",
    "convert_to_nnUNet_2023_fake(source_file, destination_folder)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ff9697e",
   "metadata": {},
   "source": [
    "#### Creating the dataset.json files"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "d63acdf8",
   "metadata": {},
   "outputs": [],
   "source": [
    "destination_folder = './nnUNet_raw/Dataset232_BraTS_2023_rGANs'  # Destination folder path  \n",
    "\n",
    "json_content = {\n",
    "    \"channel_names\": {\n",
    "        \"0\": \"t1c\",\n",
    "        \"1\": \"t1\",\n",
    "        \"2\": \"t2f\",\n",
    "        \"3\": \"t2\"\n",
    "    },\n",
    "    \"labels\": {\n",
    "        \"background\": 0,\n",
    "        \"whole tumor\": [\n",
    "            1,\n",
    "            2,\n",
    "            3\n",
    "        ],\n",
    "        \"tumor core\": [\n",
    "            2,\n",
    "            3\n",
    "        ],\n",
    "        \"enhancing tumor\": 3,\n",
    "    },\n",
    "    \"numTraining\": len(os.listdir(os.path.join(destination_folder, \"labelsTr\"))),\n",
    "    \"file_ending\": \".nii.gz\",\n",
    "    \"regions_class_order\": [\n",
    "        1,\n",
    "        2,\n",
    "        3\n",
    "    ]\n",
    "}\n",
    "\n",
    "# Save dictionary to a JSON file\n",
    "with open(f'{destination_folder}/dataset.json', 'w') as json_file:\n",
    "    json.dump(json_content, json_file, indent=4)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## BraTS-ISBI 2024 GoAT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5a7d4c8c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import shutil\n",
    "import os\n",
    "import SimpleITK as sitk\n",
    "import numpy as np\n",
    "\n",
    "def convert_to_nnUNet_2023_real(source_file, destination_folder):\n",
    "    os.makedirs(os.path.join(destination_folder, \"imagesTr\"), exist_ok=True)\n",
    "    os.makedirs(os.path.join(destination_folder, \"labelsTr\"), exist_ok=True)\n",
    "    for folder in os.listdir(source_file):\n",
    "        t1c_name = f\"{folder}-t1c.nii.gz\"\n",
    "        t1c_path = os.path.join(source_file, folder, t1c_name)\n",
    "        new_t1c_name = f\"{folder}_0000.nii.gz\"\n",
    "        destination_t1c = os.path.join(destination_folder, \"imagesTr\", new_t1c_name)\n",
    "        shutil.copy(t1c_path, destination_t1c)\n",
    "        \n",
    "        t1n_name = f\"{folder}-t1n.nii.gz\"\n",
    "        t1n_path = os.path.join(source_file, folder, t1n_name)\n",
    "        new_t1n_name = f\"{folder}_0001.nii.gz\"\n",
    "        destination_t1n = os.path.join(destination_folder, \"imagesTr\", new_t1n_name)\n",
    "        shutil.copy(t1n_path, destination_t1n)\n",
    "        \n",
    "        t2f_name = f\"{folder}-t2f.nii.gz\"\n",
    "        t2f_path = os.path.join(source_file, folder, t2f_name)\n",
    "        new_t2f_name = f\"{folder}_0002.nii.gz\"\n",
    "        destination_t2f = os.path.join(destination_folder, \"imagesTr\", new_t2f_name)\n",
    "        shutil.copy(t2f_path, destination_t2f)\n",
    "        \n",
    "        t2w_name = f\"{folder}-t2w.nii.gz\"\n",
    "        t2w_path = os.path.join(source_file, folder, t2w_name)\n",
    "        new_t2w_name = f\"{folder}_0003.nii.gz\"\n",
    "        destination_t2w = os.path.join(destination_folder, \"imagesTr\", new_t2w_name)\n",
    "        shutil.copy(t2w_path, destination_t2w)\n",
    "        \n",
    "\n",
    "        seg_name = f\"{folder}-seg.nii.gz\"\n",
    "        seg_path = os.path.join(source_file, folder, seg_name)\n",
    "        new_seg_name = f\"{folder}.nii.gz\"\n",
    "        destination_seg = os.path.join(destination_folder, \"labelsTr\", new_seg_name)\n",
    "        copy_BraTS_segmentation_and_convert_labels_to_nnUNet_2023(in_file=seg_path, out_file=destination_seg)\n",
    "\n",
    "# For real data\n",
    "source_file = '../GliGAN/DataSet/ISBI2024-BraTS-GoAT-TrainingData'  # Path to the source file\n",
    "destination_folder = './nnUNet_raw/Dataset240_BraTS_ISBI_GoAT_2024_rGANs'  # Destination folder path  \n",
    "convert_to_nnUNet_2023_real(source_file, destination_folder)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "87961370",
   "metadata": {},
   "outputs": [],
   "source": [
    "def convert_to_nnUNet_2023_fake(source_file, destination_folder):\n",
    "    os.makedirs(os.path.join(destination_folder, \"imagesTr\"), exist_ok=True)\n",
    "    os.makedirs(os.path.join(destination_folder, \"labelsTr\"), exist_ok=True)\n",
    "    for folder in os.listdir(source_file):\n",
    "        t1c_name = f\"{folder}-scan_t1ce.nii.gz\"\n",
    "        t1c_path = os.path.join(source_file, folder, t1c_name)\n",
    "        new_t1c_name = f\"{folder}_0000.nii.gz\"\n",
    "        destination_t1c = os.path.join(destination_folder, \"imagesTr\", new_t1c_name)\n",
    "        shutil.copy(t1c_path, destination_t1c)\n",
    "        \n",
    "        t1n_name = f\"{folder}-scan_t1.nii.gz\"\n",
    "        t1n_path = os.path.join(source_file, folder, t1n_name)\n",
    "        new_t1n_name = f\"{folder}_0001.nii.gz\"\n",
    "        destination_t1n = os.path.join(destination_folder, \"imagesTr\", new_t1n_name)\n",
    "        shutil.copy(t1n_path, destination_t1n)\n",
    "        \n",
    "        t2f_name = f\"{folder}-scan_flair.nii.gz\"\n",
    "        t2f_path = os.path.join(source_file, folder, t2f_name)\n",
    "        new_t2f_name = f\"{folder}_0002.nii.gz\"\n",
    "        destination_t2f = os.path.join(destination_folder, \"imagesTr\", new_t2f_name)\n",
    "        shutil.copy(t2f_path, destination_t2f)\n",
    "        \n",
    "        t2w_name = f\"{folder}-scan_t2.nii.gz\"\n",
    "        t2w_path = os.path.join(source_file, folder, t2w_name)\n",
    "        new_t2w_name = f\"{folder}_0003.nii.gz\"\n",
    "        destination_t2w = os.path.join(destination_folder, \"imagesTr\", new_t2w_name)\n",
    "        shutil.copy(t2w_path, destination_t2w)\n",
    "        \n",
    "\n",
    "        seg_name = f\"{folder}-seg.nii.gz\"\n",
    "        seg_path = os.path.join(source_file, folder, seg_name)\n",
    "        new_seg_name = f\"{folder}.nii.gz\"\n",
    "        destination_seg = os.path.join(destination_folder, \"labelsTr\", new_seg_name)\n",
    "        copy_BraTS_segmentation_and_convert_labels_to_nnUNet_2023(in_file=seg_path, out_file=destination_seg)\n",
    "\n",
    "# For fake data\n",
    "source_file = '../GliGAN/Checkpoint/brats_goat_2024/Synthetic_dataset_random_labels'  # Path to the source file\n",
    "destination_folder = './nnUNet_raw/Dataset240_BraTS_ISBI_GoAT_2024_rGANs'  # Destination folder path  \n",
    "convert_to_nnUNet_2023_fake(source_file, destination_folder)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76421002",
   "metadata": {},
   "source": [
    "#### Creating the dataset.json files"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "22864265",
   "metadata": {},
   "outputs": [],
   "source": [
    "destination_folder = './nnUNet_raw/Dataset240_BraTS_ISBI_GoAT_2024_rGANs'  # Destination folder path  \n",
    "\n",
    "json_content = {\n",
    "    \"channel_names\": {\n",
    "        \"0\": \"t1c\",\n",
    "        \"1\": \"t1\",\n",
    "        \"2\": \"t2f\",\n",
    "        \"3\": \"t2\"\n",
    "    },\n",
    "    \"labels\": {\n",
    "        \"background\": 0,\n",
    "        \"whole tumor\": [\n",
    "            1,\n",
    "            2,\n",
    "            3\n",
    "        ],\n",
    "        \"tumor core\": [\n",
    "            2,\n",
    "            3\n",
    "        ],\n",
    "        \"enhancing tumor\": 3\n",
    "    },\n",
    "    \"numTraining\": len(os.listdir(os.path.join(destination_folder, \"labelsTr\"))),\n",
    "    \"file_ending\": \".nii.gz\",\n",
    "    \"regions_class_order\": [\n",
    "        1,\n",
    "        2,\n",
    "        3\n",
    "    ]\n",
    "}\n",
    "\n",
    "# Save dictionary to a JSON file\n",
    "with open(f'{destination_folder}/dataset.json', 'w') as json_file:\n",
    "    json.dump(json_content, json_file, indent=4)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0694309",
   "metadata": {},
   "source": [
    "## BraTS 2024 Task 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb3e2eb5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import shutil\n",
    "import os\n",
    "import SimpleITK as sitk\n",
    "import numpy as np\n",
    "\n",
    "def convert_to_nnUNet_2024(source_file, destination_folder):\n",
    "    os.makedirs(os.path.join(destination_folder, \"imagesTr\"), exist_ok=True)\n",
    "    os.makedirs(os.path.join(destination_folder, \"labelsTr\"), exist_ok=True)\n",
    "    for folder in os.listdir(source_file):\n",
    "        t1c_name = f\"{folder}-t1c.nii.gz\"\n",
    "        t1c_path = os.path.join(source_file, folder, t1c_name)\n",
    "        new_t1c_name = f\"{folder}_0000.nii.gz\"\n",
    "        destination_t1c = os.path.join(destination_folder, \"imagesTr\", new_t1c_name)\n",
    "        shutil.copy(t1c_path, destination_t1c)\n",
    "        \n",
    "        t1n_name = f\"{folder}-t1n.nii.gz\"\n",
    "        t1n_path = os.path.join(source_file, folder, t1n_name)\n",
    "        new_t1n_name = f\"{folder}_0001.nii.gz\"\n",
    "        destination_t1n = os.path.join(destination_folder, \"imagesTr\", new_t1n_name)\n",
    "        shutil.copy(t1n_path, destination_t1n)\n",
    "        \n",
    "        t2f_name = f\"{folder}-t2f.nii.gz\"\n",
    "        t2f_path = os.path.join(source_file, folder, t2f_name)\n",
    "        new_t2f_name = f\"{folder}_0002.nii.gz\"\n",
    "        destination_t2f = os.path.join(destination_folder, \"imagesTr\", new_t2f_name)\n",
    "        shutil.copy(t2f_path, destination_t2f)\n",
    "        \n",
    "        t2w_name = f\"{folder}-t2w.nii.gz\"\n",
    "        t2w_path = os.path.join(source_file, folder, t2w_name)\n",
    "        new_t2w_name = f\"{folder}_0003.nii.gz\"\n",
    "        destination_t2w = os.path.join(destination_folder, \"imagesTr\", new_t2w_name)\n",
    "        shutil.copy(t2w_path, destination_t2w)\n",
    "        \n",
    "\n",
    "        seg_name = f\"{folder}-seg.nii.gz\"\n",
    "        seg_path = os.path.join(source_file, folder, seg_name)\n",
    "        new_seg_name = f\"{folder}.nii.gz\"\n",
    "        destination_seg = os.path.join(destination_folder, \"labelsTr\", new_seg_name)\n",
    "        copy_BraTS_segmentation_and_convert_labels_to_nnUNet_2024(in_file=seg_path, out_file=destination_seg)\n",
    "\n",
    "# For real data\n",
    "source_file = '../GliGAN/DataSet/BraTS2024-BraTS-GLI-TrainingData'  # Path to the source file\n",
    "destination_folder = './nnUNet_raw/Dataset242_BraTS_2024_rGANs'  # Destination folder path  \n",
    "convert_to_nnUNet_2024(source_file, destination_folder)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "3346c40f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def convert_to_nnUNet_2024_fake(source_file, destination_folder):\n",
    "    os.makedirs(os.path.join(destination_folder, \"imagesTr\"), exist_ok=True)\n",
    "    os.makedirs(os.path.join(destination_folder, \"labelsTr\"), exist_ok=True)\n",
    "    for folder in os.listdir(source_file):\n",
    "        t1c_name = f\"{folder}-scan_t1ce.nii.gz\"\n",
    "        t1c_path = os.path.join(source_file, folder, t1c_name)\n",
    "        new_t1c_name = f\"{folder}_0000.nii.gz\"\n",
    "        destination_t1c = os.path.join(destination_folder, \"imagesTr\", new_t1c_name)\n",
    "        shutil.copy(t1c_path, destination_t1c)\n",
    "        \n",
    "        t1n_name = f\"{folder}-scan_t1.nii.gz\"\n",
    "        t1n_path = os.path.join(source_file, folder, t1n_name)\n",
    "        new_t1n_name = f\"{folder}_0001.nii.gz\"\n",
    "        destination_t1n = os.path.join(destination_folder, \"imagesTr\", new_t1n_name)\n",
    "        shutil.copy(t1n_path, destination_t1n)\n",
    "        \n",
    "        t2f_name = f\"{folder}-scan_flair.nii.gz\"\n",
    "        t2f_path = os.path.join(source_file, folder, t2f_name)\n",
    "        new_t2f_name = f\"{folder}_0002.nii.gz\"\n",
    "        destination_t2f = os.path.join(destination_folder, \"imagesTr\", new_t2f_name)\n",
    "        shutil.copy(t2f_path, destination_t2f)\n",
    "        \n",
    "        t2w_name = f\"{folder}-scan_t2.nii.gz\"\n",
    "        t2w_path = os.path.join(source_file, folder, t2w_name)\n",
    "        new_t2w_name = f\"{folder}_0003.nii.gz\"\n",
    "        destination_t2w = os.path.join(destination_folder, \"imagesTr\", new_t2w_name)\n",
    "        shutil.copy(t2w_path, destination_t2w)\n",
    "        \n",
    "\n",
    "        seg_name = f\"{folder}-seg.nii.gz\"\n",
    "        seg_path = os.path.join(source_file, folder, seg_name)\n",
    "        new_seg_name = f\"{folder}.nii.gz\"\n",
    "        destination_seg = os.path.join(destination_folder, \"labelsTr\", new_seg_name)\n",
    "        copy_BraTS_segmentation_and_convert_labels_to_nnUNet_2024(in_file=seg_path, out_file=destination_seg)\n",
    "\n",
    "# For fake data\n",
    "source_file = '../GliGAN/Checkpoint/brats2024/Synthetic_dataset_random_labels'  # Path to the source file\n",
    "destination_folder = './nnUNet_raw/Dataset242_BraTS_2024_rGANs'  # Destination folder path  \n",
    "convert_to_nnUNet_2024_fake(source_file, destination_folder)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "663b80dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the mednext folder\n",
    "nnUNet_folder_raw = './nnUNet_raw/Dataset242_BraTS_2024_rGANs'\n",
    "nnUNet_raw_data_folder = './nnUNet_raw/nnUNet_raw_data/Task242_BraTS_2024_rGANs'\n",
    "\n",
    "# Copy the entire folder and its contents\n",
    "if os.path.exists(nnUNet_raw_data_folder):\n",
    "    shutil.rmtree(nnUNet_raw_data_folder)\n",
    "shutil.copytree(nnUNet_folder_raw, nnUNet_raw_data_folder)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a7280d2",
   "metadata": {},
   "source": [
    "#### Creating the dataset.json files"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "73991934",
   "metadata": {},
   "outputs": [],
   "source": [
    "# For nnUNet\n",
    "\n",
    "destination_folder = './nnUNet_raw/Dataset242_BraTS_2024_rGANs'  # Destination folder path  \n",
    "\n",
    "json_content = {\n",
    "    \"channel_names\": {\n",
    "        \"0\": \"t1c\",\n",
    "        \"1\": \"t1\",\n",
    "        \"2\": \"t2f\",\n",
    "        \"3\": \"t2\"\n",
    "    },\n",
    "    \"labels\": {\n",
    "        \"background\": 0,\n",
    "        \"whole tumor\": [\n",
    "            1,\n",
    "            2,\n",
    "            3\n",
    "        ],\n",
    "        \"tumor core\": [\n",
    "            2,\n",
    "            3\n",
    "        ],\n",
    "        \"enhancing tumor\": 3,\n",
    "        \"RC\": 4\n",
    "    },\n",
    "    \"numTraining\": len(os.listdir(os.path.join(destination_folder, \"labelsTr\"))),\n",
    "    \"file_ending\": \".nii.gz\",\n",
    "    \"regions_class_order\": [\n",
    "        1,\n",
    "        2,\n",
    "        3,\n",
    "        4\n",
    "    ]\n",
    "}\n",
    "\n",
    "# Save dictionary to a JSON file\n",
    "with open(f'{destination_folder}/dataset.json', 'w') as json_file:\n",
    "    json.dump(json_content, json_file, indent=4)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "db96bb72",
   "metadata": {},
   "outputs": [],
   "source": [
    "# For MedNeXt\n",
    "channel_names= {\n",
    "        \"0\": \"t1c\",\n",
    "        \"1\": \"t1\",\n",
    "        \"2\": \"t2f\",\n",
    "        \"3\": \"t2\"\n",
    "    }\n",
    "labels = {\n",
    "        0 : \"Background\",\n",
    "        1 : \"SNFH\",\n",
    "        2 : \"NETC\",\n",
    "        3 : \"ET \",\n",
    "        4 : \"RC\"\n",
    "    }\n",
    "\n",
    "modalities = ('T1C', 'T1', 'T2', 'FLAIR')\n",
    "\n",
    "generate_dataset_json(output_file = \"./nnUNet_raw/nnUNet_raw_data/Task242_BraTS_2024_rGANs/dataset.json\", \n",
    "                    imagesTr_dir = \"./nnUNet_raw/nnUNet_raw_data/Task242_BraTS_2024_rGANs/imagesTr\", \n",
    "                    imagesTs_dir = None,\n",
    "                    modalities = modalities,\n",
    "                    labels = labels, \n",
    "                    dataset_name = \"Task242_BraTS_2024_rGANs\",\n",
    "                    dataset_description = \"Task242_BraTS_2024_rGANs dataset\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cdedff7c",
   "metadata": {},
   "source": [
    "## BraTS 2024 Task 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "df222673",
   "metadata": {},
   "outputs": [],
   "source": [
    "import shutil\n",
    "import os\n",
    "import SimpleITK as sitk\n",
    "import numpy as np\n",
    "\n",
    "def convert_to_nnUNet_2024_meningioma(source_file, destination_folder):\n",
    "    os.makedirs(os.path.join(destination_folder, \"imagesTr\"), exist_ok=True)\n",
    "    os.makedirs(os.path.join(destination_folder, \"labelsTr\"), exist_ok=True)\n",
    "    for folder in os.listdir(source_file):\n",
    "        t1c_name = f\"{folder}_t1c.nii.gz\"\n",
    "        t1c_path = os.path.join(source_file, folder, t1c_name)\n",
    "        gtv_name = f\"{folder}_gtv.nii.gz\"\n",
    "        gtv_path = os.path.join(source_file, folder, gtv_name)\n",
    "        \n",
    "        # Define the full path for the new file\n",
    "        new_t1c_name = f\"{folder}_0000.nii.gz\"\n",
    "        destination_t1c = os.path.join(destination_folder, \"imagesTr\", new_t1c_name)\n",
    "        shutil.copy(t1c_path, destination_t1c)\n",
    "        \n",
    "        new_gtv_name = f\"{folder}.nii.gz\"\n",
    "        destination_gtv = os.path.join(destination_folder, \"labelsTr\", new_gtv_name)\n",
    "        shutil.copy(gtv_path, destination_gtv)\n",
    "\n",
    "# For real data\n",
    "source_file = '../GliGAN/DataSet/BraTS-MEN-RT-Train-v2'  # Path to the source file\n",
    "destination_folder = './nnUNet_raw/Task244_BraTS_2024_meningioma_rGANs'  # Destination folder path  \n",
    "convert_to_nnUNet_2024_meningioma(source_file, destination_folder)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "64583749",
   "metadata": {},
   "outputs": [],
   "source": [
    "def convert_to_nnUNet_2024_meningioma(source_file, destination_folder):\n",
    "    os.makedirs(os.path.join(destination_folder, \"imagesTr\"), exist_ok=True)\n",
    "    os.makedirs(os.path.join(destination_folder, \"labelsTr\"), exist_ok=True)\n",
    "    for folder in os.listdir(source_file):\n",
    "        t1c_name = f\"{folder}-scan_t1ce.nii.gz\"\n",
    "        t1c_path = os.path.join(source_file, folder, t1c_name)\n",
    "        gtv_name = f\"{folder}-seg.nii.gz\"\n",
    "        gtv_path = os.path.join(source_file, folder, gtv_name)\n",
    "        \n",
    "        # Define the full path for the new file\n",
    "        new_t1c_name = f\"{folder}_0000.nii.gz\"\n",
    "        destination_t1c = os.path.join(destination_folder, \"imagesTr\", new_t1c_name)\n",
    "        shutil.copy(t1c_path, destination_t1c)\n",
    "        \n",
    "        new_gtv_name = f\"{folder}.nii.gz\"\n",
    "        destination_gtv = os.path.join(destination_folder, \"labelsTr\", new_gtv_name)\n",
    "        shutil.copy(gtv_path, destination_gtv)\n",
    "\n",
    "# For fake data\n",
    "source_file = '../GliGAN/Checkpoint/brats2024_meningioma/Synthetic_dataset_random_labels'  # Path to the source file\n",
    "destination_folder = './nnUNet_raw/Dataset244_BraTS_2024_meningioma_rGANs'  # Destination folder path  \n",
    "convert_to_nnUNet_2024_meningioma(source_file, destination_folder)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56c79b11",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the mednext folder\n",
    "nnUNet_folder_raw = './nnUNet_raw/Dataset244_BraTS_2024_meningioma_rGANs'\n",
    "nnUNet_raw_data_folder = './nnUNet_raw/nnUNet_raw_data/Task244_BraTS_2024_meningioma_rGANs'\n",
    "\n",
    "# Copy the entire folder and its contents\n",
    "shutil.copytree(nnUNet_folder_raw, nnUNet_raw_data_folder)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb23ad94",
   "metadata": {},
   "source": [
    "#### Creating the dataset.json files"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "8cdd23d4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# For nnUNet\n",
    "\n",
    "destination_folder = './nnUNet_raw/Dataset244_BraTS_2024_meningioma_rGANs'  # Destination folder path  \n",
    "\n",
    "json_content = {\n",
    "    \"channel_names\": {\n",
    "        \"0\": \"t1c\"\n",
    "    },\n",
    "    \"labels\": {\n",
    "        \"background\": 0,\n",
    "        \"GTV\": 1\n",
    "    },\n",
    "    \"numTraining\": len(os.listdir(os.path.join(destination_folder, \"labelsTr\"))),\n",
    "    \"file_ending\": \".nii.gz\",\n",
    "}\n",
    "\n",
    "# Save dictionary to a JSON file\n",
    "with open(f'{destination_folder}/dataset.json', 'w') as json_file:\n",
    "    json.dump(json_content, json_file, indent=4)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "bf4a5f14",
   "metadata": {},
   "outputs": [],
   "source": [
    "# For MedNeXt\n",
    "channel_names= {\n",
    "        \"0\": \"t1c\"\n",
    "    }\n",
    "labels = {\n",
    "        0 : \"Background\",\n",
    "        1 : \"GTV\",\n",
    "\n",
    "    }\n",
    "\n",
    "modalities = ('T1C',)\n",
    "\n",
    "generate_dataset_json(output_file = \"./nnUNet_raw/nnUNet_raw_data/Task244_BraTS_2024_meningioma_rGANs/dataset.json\", \n",
    "                    imagesTr_dir = \"./nnUNet_raw/nnUNet_raw_data/Task244_BraTS_2024_meningioma_rGANs/imagesTr\", \n",
    "                    imagesTs_dir = None,\n",
    "                    modalities = modalities,\n",
    "                    labels = labels, \n",
    "                    dataset_name = \"Task244_BraTS_2024_meningioma_rGANs\",\n",
    "                    dataset_description = \"Task244_BraTS_2024_meningioma_rGANs\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e954861e",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "brats2023",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
